<?php

require_once 'dbutils.php';
require_once 'RestUtils.php';
require_once 'Base.php';

class UserJourneys extends Base
{

    function GET($matches)
    {
        $req = RestUtils::processRequest('GET');
        $req_vars = $req->getRequestVars();
        $db_vars = dbutils::translate_rest_params($req_vars);
        $res = $this->selectUserJourneys($db_vars);
        if ($res['code'] == 0)
            RestUtils::sendResponse(200, $res['result'], 'application/json');
        else
            RestUtils::sendResponse(404, dbutils::error_to_json($res['code'], $res['message']), 'application/json');
    }

    function POST($matches)
    {
        $req = RestUtils::processRequest('POST');
        $req_vars = $req->getRequestVars();
        $db_vars = dbutils::translate_rest_params($req_vars);
        $res = $this->insertUserJourney($db_vars);
        if ($res['code'] == 0)
            RestUtils::sendResponse(200, $res['result'], 'application/json');
        else
            RestUtils::sendResponse(404, dbutils::error_to_json($res['code'], $res['message']), 'application/json');
    }

    function PUT($matches)
    {
        $req = RestUtils::processRequest('PUT');
        $req_vars = $req->getRequestVars();
        $db_vars = dbutils::translate_rest_params($req_vars);
        $res = $this->updateUserJourney($db_vars);
        if ($res['code'] == 0)
            RestUtils::sendResponse(200);
        else
            RestUtils::sendResponse(404, dbutils::error_to_json($res['code'], $res['message']), 'application/json');
    }

    function DELETE($matches)
    {
        $req = RestUtils::processRequest('DELETE');
        $req_vars = $req->getRequestVars();
        $db_vars = dbutils::translate_rest_params($req_vars);
        $res = $this->deleteUserJourney($db_vars);
        if ($res['code'] == 0)
            RestUtils::sendResponse(200);
        else
            RestUtils::sendResponse(404, dbutils::error_to_json($res['code'], $res['message']), 'application/json');
    }

    private function selectUserJourneys($values)
    {
        $code = 0;
        $msg = '';
        $result = null;
        try {
            if (!$values)
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            if (!array_key_exists('id_user', $values))
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            $db_handle = @pg_pconnect(dbutils::$conn_string);

            $query = "SELECT j.id AS id_journey,
                             to_char(j.departure_datetime,'YYYY-MM-DD HH24:MI') AS departure_datetime,
                             j.passengers, j.luggages,
                             r.departure_lat, r.departure_lng,
                             r.arriva_lat, r.arriva_lng,
                             r.route_lenght_mt,
                             r.departure_addr, r.arriva_addr,
                             j.status AS journey_status
                      FROM user_journeys uj, journeys j, routes r
                      WHERE uj.id_user = {$values['id_user']}
                      AND uj.id_journey = j.id
                      AND j.id_route = r.id";
            if (array_key_exists('fl_owner', $values))
                $query .= " AND uj.fl_owner = '{$values['fl_owner']}'";

            $result = @pg_query($db_handle, $query);
            if ($result)
                $result = dbutils::dbresult_to_json($result);
            else {
                $code = -1;
                $msg = 'no db records found ' . @pg_last_error($db_handle);
            }
            @pg_close($db_handle);
        } catch (Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }
        return array('code' => $code, 'message' => $msg, 'result' => $result);
    }

    private function insertUserJourney($values)
    {
        $code = 0;
        $msg = '';
        $result = null;
        try {
            if (!$values)
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            if (!array_key_exists('departure_lat', $values)
                || !array_key_exists('departure_lng', $values)
                || !array_key_exists('departure_addr', $values)
                || !array_key_exists('arriva_lat', $values)
                || !array_key_exists('arriva_lng', $values)
                || !array_key_exists('arriva_addr', $values)
                || !array_key_exists('route_lenght_mt', $values)
                || !array_key_exists('departure_datetime', $values)
                || !array_key_exists('passengers', $values)
                || !array_key_exists('luggages', $values)
                || !array_key_exists('id_user', $values)
            )
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            $values['journey_status'] = "OPEN";

            $db_handle = @pg_pconnect(dbutils::$conn_string);

            $res = @pg_query($db_handle, "SELECT nextval('routes_id_seq') as key");
            if ($res) {
                $row = @pg_fetch_array($res, 0);
                $id_route = $row['key'];
                $res = @pg_query($db_handle, "SELECT nextval('journeys_id_seq') as key");
                if ($res) {
                    $row = @pg_fetch_array($res, 0);
                    $id_journey = $row['key'];
                }
            }
            if ($id_journey && $id_route) {
                $insert = "INSERT INTO routes (id, departure_lat, departure_lng,
                                                 arriva_lat, arriva_lng, route_lenght_mt, departure_addr, arriva_addr)
                                        VALUES ({$id_route},{$values['departure_lat']},{$values['departure_lng']},
                                                {$values['arriva_lat']},{$values['arriva_lng']},
                                                {$values['route_lenght_mt']}, '{$values['departure_addr']}', '{$values['arriva_addr']}');";
                $insert .= " INSERT INTO journeys (id, departure_datetime,
                                                  passengers, luggages,
                                                  status, id_route)
                                        VALUES ({$id_journey},
                                               TIMESTAMP '{$values['departure_datetime']}',
                                               '{$values['passengers']}', '{$values['luggages']}',
                                               '{$values['journey_status']}', {$id_route});";
                $insert .= " INSERT INTO user_journeys (id_user, id_journey, fl_owner)
                                        VALUES ({$values['id_user']}, {$id_journey}, '1');";

                $result = @pg_query($db_handle, $insert);
                if ($result)
                    $result = json_encode(array('idJourney' => $id_journey));
                else {
                    $code = -1;
                    $msg = 'inserting records not possible ' . @pg_last_error($db_handle);
                }
            } else {
                $code = -1;
                $msg = 'error generating idJourney or idRoute ' . @pg_last_error($db_handle);
            }
            @pg_close($db_handle);
        } catch (Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }
        return array('code' => $code, 'message' => $msg, 'result' => $result);
    }

    private function updateUserJourney($values)
    {
        $code = 0;
        $msg = '';
        $result = null;
        try {
            if (!$values)
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            if (!array_key_exists('departure_lat', $values)
                || !array_key_exists('departure_lng', $values)
                || !array_key_exists('departure_addr', $values)
                || !array_key_exists('arriva_lat', $values)
                || !array_key_exists('arriva_lng', $values)
                || !array_key_exists('arriva_addr', $values)
                || !array_key_exists('route_lenght_mt', $values)
                || !array_key_exists('departure_datetime', $values)
                || !array_key_exists('passengers', $values)
                || !array_key_exists('luggages', $values)
                || !array_key_exists('journey_status', $values)
                || !array_key_exists('id_journey', $values)
            )
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            $db_handle = @pg_pconnect(dbutils::$conn_string);

            $res = @pg_query($db_handle, "SELECT id_route as key
                                         FROM journeys
                                         WHERE id = {$values['id_journey']}");
            if ($res && @pg_num_rows($res) > 0) {
                $row = @pg_fetch_array($res, 0);
                $id_route = $row['key'];
            }
            if ($id_route) {
                $update = "UPDATE routes
                                        SET departure_lat={$values['departure_lat']},
                                            departure_lng={$values['departure_lng']},
                                            departure_addr={$values['departure_addr']},
                                            arriva_lat={$values['arriva_lat']},
                                            arriva_lng={$values['arriva_lng']},
                                            arriva_addr={$values['arriva_addr']},
                                            route_lenght_mt={$values['route_lenght_mt']}
                                        WHERE id={$id_route};";
                $update .= " UPDATE journeys
                                         SET departure_datetime=TIMESTAMP '{$values['departure_datetime']}',
                                             passengers='{$values['passengers']}',
                                             luggages='{$values['luggages']}',
                                             status='{$values['journey_status']}'
                                        WHERE id={$values['id_journey']};";

                $result = @pg_query($db_handle, $update);
                if (!$result) {
                    $code = -1;
                    $msg = 'updating records not possible ' . @pg_last_error($db_handle);
                }
            } else {
                $code = -1;
                $msg = 'error retrieving idRoute ' . @pg_last_error($db_handle);
            }
            @pg_close($db_handle);
        } catch (Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }
        return array('code' => $code, 'message' => $msg, 'result' => $result);
    }

    private function deleteUserJourney($values)
    {
        $code = 0;
        $msg = '';
        $result = null;
        try {
            if (!$values)
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            if (!array_key_exists('id_journey', $values))
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            $db_handle = @pg_pconnect(dbutils::$conn_string);

            $res = @pg_query($db_handle, "SELECT id_route as key
                                         FROM journeys
                                         WHERE id = {$values['id_journey']}");
            if ($res && @pg_num_rows($res) > 0) {
                $row = @pg_fetch_array($res, 0);
                $id_route = $row['key'];
            }
            if ($id_route) {
                $delete = "DELETE FROM messages
                                        WHERE id_journey={$values['id_journey']};";
                $delete .= "DELETE FROM user_journeys
                                        WHERE id_journey={$values['id_journey']};";
                $delete .= "DELETE FROM journeys
                                        WHERE id={$values['id_journey']};";
                $delete .= "DELETE FROM routes
                                        WHERE id={$id_route};";

                $result = @pg_query($db_handle, $delete);
                if (!$result) {
                    $code = -1;
                    $msg = 'deleting records not possible ' . @pg_last_error($db_handle);
                }
            } else {
                $code = -1;
                $msg = 'error retrieving idRoute ' . @pg_last_error($db_handle);
            }
            @pg_close($db_handle);
        } catch (Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }
        return array('code' => $code, 'message' => $msg, 'result' => $result);
    }
}

?>